package com.primb.bench.project.search.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bruce.pickerview.popwindow.DatePickerPopWin;
import com.primb.baselibs.util.FormatUtils;
import com.primb.baselibs.view.AutoToolbar;
import com.primb.bench.R;
import com.primb.bench.base.SwipeBaseActivity;
import com.primb.bench.common.constant.AppConstant;
import com.primb.bench.common.dialog.SelectListDialog;
import com.primb.bench.common.module.repository.SearchConditionRepository;
import com.primb.bench.common.override.HttpSubscriber;
import com.primb.bench.project.home.entity.KeyEntity;
import com.primb.bench.project.search.entity.RequestPriceEntity;
import com.primb.netlibs.exception.ApiException;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by Chen on 2017/8/1.
 * 功能描述：
 */

public class PriceConditionActivity extends SwipeBaseActivity {

    @BindView(R.id.title_bar)
    TextView titleBar;
    @BindView(R.id.iv_top)
    ImageView ivTop;
    @BindView(R.id.tool_bar)
    AutoToolbar toolBar;
    @BindView(R.id.et_condition_client_number)
    EditText etConditionClientNumber;
    @BindView(R.id.et_condition_client_name)
    EditText etConditionClientName;
    @BindView(R.id.tv_condition_start_date)
    TextView tvConditionStartDate;
    @BindView(R.id.tv_condition_end_date)
    TextView tvConditionEndDate;
    @BindView(R.id.tv_condition_loan_type)
    TextView tvConditionLoanType;
    @BindView(R.id.tv_condition_price_type)
    TextView tvConditionPriceType;
    @BindView(R.id.tv_condition_date_unit)
    TextView tvConditionDateUnit;
    @BindView(R.id.tv_condition_part)
    TextView tvConditionPricePart;
    @BindView(R.id.btn_condition_search)
    Button btnConditionSearch;
    @BindView(R.id.et_condition_loan_date)
    EditText etConditionLoanDate;
    private RequestPriceEntity info;
    private CompositeSubscription subscription;
    private ArrayList<KeyEntity> priceList;
    private ArrayList<KeyEntity> unitList;

    @Override
    protected void onBaseIntent() {
        super.onBaseIntent();
        info = getIntent().getParcelableExtra("info");
    }

    @Override
    protected int onBaseLayoutId(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_search_condition;
    }

    @Override
    protected void onBaseBindView() {
        titleBar.setText("查询条件");
        toolBar.setNavigationOnClickListener(v -> PriceConditionActivity.this.finish());
        ivTop.setImageResource(R.mipmap.reset_icon);
        ivTop.setVisibility(View.VISIBLE);
        if (info.getCustId() != null && !info.getCustId().equals("")) {
            etConditionClientNumber.setText(info.getCustId());
        }
        if (info.getCustName() != null && !info.getCustName().equals("")) {
            etConditionClientName.setText(info.getCustName());
        }
        if (info.getStartDate() != null && !info.getStartDate().equals("")) {
            tvConditionStartDate.setText(info.getStartDate());
            tvConditionStartDate.setTextColor(ContextCompat.getColor(PriceConditionActivity.this, R.color.app_font));
        }
        if (info.getEndDate() != null && !info.getEndDate().equals("")) {
            tvConditionEndDate.setText(info.getEndDate());
            tvConditionEndDate.setTextColor(ContextCompat.getColor(PriceConditionActivity.this, R.color.app_font));
        }
        if (info.getLnPrdId() != null && !info.getLnPrdId().equals("")) {
            tvConditionLoanType.setText(info.getLnPrdName());
            tvConditionLoanType.setTextColor(ContextCompat.getColor(PriceConditionActivity.this, R.color.app_font));
        }
        if (info.getPriceType() != null && !info.getPriceType().equals("")) {
            tvConditionPriceType.setText((info.getPriceType().equals("01") ? "贷款定价试算" : "贷款定价申请"));
            tvConditionPriceType.setTextColor(ContextCompat.getColor(PriceConditionActivity.this, R.color.app_font));
        }
        if (info.getLnTrem() != null && !info.getLnTrem().equals("")) {
            etConditionLoanDate.setText(info.getLnTrem());
        }
        if (info.getTremUtil() != null && !info.getTremUtil().equals("")) {
            tvConditionDateUnit.setText(info.getTremUtil().equals("0") ? "年" : "月");
            tvConditionDateUnit.setTextColor(ContextCompat.getColor(PriceConditionActivity.this, R.color.app_font));
        } else {
            info.setTremUtil("0");
        }
        if (info.getOrgId() != null && !info.getOrgId().equals("")) {
            tvConditionPricePart.setText(info.getOrgName());
            tvConditionPricePart.setTextColor(ContextCompat.getColor(PriceConditionActivity.this, R.color.app_font));
        }
    }

    @Override
    protected void onLoadData() {
        subscription = new CompositeSubscription();
    }

    public void showDatePicker(int code) {
        DatePickerPopWin pickerPopWin = new DatePickerPopWin.Builder(PriceConditionActivity.this, new DatePickerPopWin.OnDatePickedListener() {
            @Override
            public void onDatePickCompleted(int year, int month, int day, String dateDesc) {
                if (code == 0) {
                    tvConditionStartDate.setText(dateDesc);
                    tvConditionStartDate.setTextColor(ContextCompat.getColor(PriceConditionActivity.this, R.color.app_font));
                    info.setStartDate(dateDesc);
                } else if (code == 1) {
                    tvConditionEndDate.setText(dateDesc);
                    tvConditionEndDate.setTextColor(ContextCompat.getColor(PriceConditionActivity.this, R.color.app_font));
                    info.setEndDate(dateDesc);
                }
            }
        }).textConfirm("确认") //text of confirm button
                .textCancel("取消") //text of cancel button
                .btnTextSize(16) // button text size
                .viewTextSize(25) // pick view text size
                .colorCancel(Color.parseColor("#999999")) //color of cancel button
                .colorConfirm(Color.parseColor("#009900"))//color of confirm button
                .minYear(1990) //min year in loop
                .maxYear(2550) // max year in loop
                .showDayMonthYear(false) // shows like dd mm yyyy (default is false)
                .dateChose(FormatUtils.DATE_FORMAT.format(new Date())) // date chose when init popwindow
                .build();
        pickerPopWin.showPopWin(this);
    }

    public SelectListDialog showPickerDialog(int code) {
        SelectListDialog listDialog = new SelectListDialog();
        listDialog.setListener((adapter, v, position) -> {
            if (code == 0) {
                tvConditionLoanType.setText(listDialog.getDataList().get(position).getKey());
                tvConditionLoanType.setTextColor(ContextCompat.getColor(PriceConditionActivity.this, R.color.app_font));
                info.setLnPrdName(listDialog.getDataList().get(position).getKey());
                info.setLnPrdId(listDialog.getDataList().get(position).getValue());
            } else if (code == 1) {
                tvConditionPriceType.setText(listDialog.getDataList().get(position).getKey());
                tvConditionPriceType.setTextColor(ContextCompat.getColor(PriceConditionActivity.this, R.color.app_font));
                info.setPriceType(listDialog.getDataList().get(position).getValue());
            } else if (code == 2) {
                tvConditionDateUnit.setText(listDialog.getDataList().get(position).getKey());
                tvConditionDateUnit.setTextColor(ContextCompat.getColor(PriceConditionActivity.this, R.color.app_font));
                info.setTremUtil(listDialog.getDataList().get(position).getValue());
            } else if (code == 3) {
                tvConditionPricePart.setText(listDialog.getDataList().get(position).getKey());
                tvConditionPricePart.setTextColor(ContextCompat.getColor(PriceConditionActivity.this, R.color.app_font));
                info.setOrgId(listDialog.getDataList().get(position).getValue());
                info.setOrgName(listDialog.getDataList().get(position).getKey());
            }
            listDialog.dismiss();
        });
        listDialog.show(getSupportFragmentManager());
        return listDialog;
    }

    private void getConditionList(int code) {
        SelectListDialog listBottomDialog = showPickerDialog(code);
        Subscription subscribe = SearchConditionRepository.getSearchCondition(code).subscribe(new HttpSubscriber<List<KeyEntity>>(this) {
            @Override
            public void onError(ApiException e) {
                showToast(e.getMessage());
                listBottomDialog.dismiss();
            }

            @Override
            public void onCompleted() {
            }

            @Override
            public void onNext(List<KeyEntity> entityList) {
                listBottomDialog.setDateList(entityList);
            }
        });
        subscription.add(subscribe);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (subscription != null) {
            subscription.clear();
        }
    }

    @OnClick({R.id.iv_top, R.id.tv_condition_start_date, R.id.tv_condition_end_date, R.id.tv_condition_loan_type, R.id.tv_condition_price_type, R.id.tv_condition_date_unit, R.id.tv_condition_part, R.id.btn_condition_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_top:
                reset();
                break;
            case R.id.tv_condition_start_date:
                showDatePicker(0);
                break;
            case R.id.tv_condition_end_date:
                showDatePicker(1);
                break;
            case R.id.tv_condition_loan_type:
                getConditionList(0);
                break;
            case R.id.tv_condition_price_type:
                getConditionList(1);
                break;
            case R.id.tv_condition_date_unit:
                getConditionList(2);
                break;
            case R.id.tv_condition_part:
                getConditionList(3);
                break;
            case R.id.btn_condition_search:
                save();
                break;
        }
    }

    private void save() {
        info.setCustId(etConditionClientNumber.getText().toString());
        info.setCustName(etConditionClientName.getText().toString());
        info.setLnTrem(etConditionLoanDate.getText().toString());

        if ((info.getEndDate() == null || info.getEndDate().equals(""))
                && (info.getStartDate() == null || info.getStartDate().equals(""))) {
            showToast("起始日和结束日至少有一个不为空");
            return;
        }

        Intent intent = new Intent();
        intent.putExtra("info", info);
        setResult(AppConstant.SEARCH_PRICE_RESULT, intent);
        this.finish();
    }

    private void reset() {
        etConditionClientName.setText("");
        etConditionClientNumber.setText("");
        etConditionLoanDate.setText("");
        tvConditionStartDate.setText("请选择");
        tvConditionStartDate.setTextColor(ContextCompat.getColor(PriceConditionActivity.this, R.color.gray_aaaaaa));
        info.setStartDate("");
        tvConditionEndDate.setText("请选择");
        tvConditionEndDate.setTextColor(ContextCompat.getColor(PriceConditionActivity.this, R.color.gray_aaaaaa));
        info.setEndDate("");
        tvConditionLoanType.setText("请选择");
        tvConditionLoanType.setTextColor(ContextCompat.getColor(PriceConditionActivity.this, R.color.gray_aaaaaa));
        info.setLnPrdName("");
        info.setLnPrdId("");
        tvConditionPriceType.setText("请选择");
        tvConditionPriceType.setTextColor(ContextCompat.getColor(PriceConditionActivity.this, R.color.gray_aaaaaa));
        info.setPriceType("");
        tvConditionDateUnit.setText("年");
        tvConditionDateUnit.setTextColor(ContextCompat.getColor(PriceConditionActivity.this, R.color.gray_aaaaaa));
        info.setTremUtil("0");
        tvConditionPricePart.setText("请选择");
        tvConditionPricePart.setTextColor(ContextCompat.getColor(PriceConditionActivity.this, R.color.gray_aaaaaa));
        info.setOrgId("");
    }
}
